/**
 * 表单规则校验工具类
 * actionType，可选值为['input', 'select']，会提示用户['请输入', '请选择']
 * ruleType，可选值为['email', 'phone', 'userName', 'password', 'verCode']，对应不同的校验规则
 * trigger，可选值为['change', 'blur']，触发校验的时机
 */
import Vue from 'vue'
import i18n from '@/i18n/'
import { isEmail, isPhone, isUserName, isPassword, isVerCode } from 'utils'

// 生成通用校验规则配置
export function rules(
  fieldKey,
  {
    required = false,
    min,
    max,
    validator,
    ruleKey,
    type,
    ruleType,
    message,
    actionType = 'input',
    trigger = 'change'
  } = {}
) {
  const ruleArr = []
  if (required) {
    ruleArr.push(
      ruleRequired(fieldKey, {
        actionType,
        trigger
      })
    )
  }
  if (min || max) {
    ruleArr.push(ruleLength(fieldKey, { min, max, trigger }))
  }
  if (validator) {
    ruleArr.push(
      ruleValidator(fieldKey, {
        validator,
        message,
        ruleKey,
        trigger
      })
    )
  }
  if (ruleType === 'email' || type === 'email') {
    ruleArr.push(
      ruleValidator(fieldKey, {
        validator: isEmail,
        ruleKey: 'rule.email',
        trigger
      })
    )
  } else if (ruleType === 'phone') {
    ruleArr.push(
      ruleValidator(fieldKey, {
        validator: isPhone,
        ruleKey: 'rule.phone',
        trigger
      })
    )
  } else if (ruleType === 'userName') {
    ruleArr.push(
      ruleValidator(fieldKey, {
        validator: isUserName,
        ruleKey: 'rule.userName',
        trigger
      })
    )
  } else if (ruleType === 'password') {
    ruleArr.push(
      ruleValidator(fieldKey, {
        validator: isPassword,
        ruleKey: 'rule.password',
        trigger
      })
    )
  } else if (ruleType === 'verCode') {
    ruleArr.push(
      ruleValidator(fieldKey, {
        validator: isVerCode,
        ruleKey: 'rule.verCode',
        trigger
      })
    )
  }
  return ruleArr
}

// 生成必填规则配置
export function ruleRequired(
  fieldKey,
  { type, actionType = 'input', trigger = 'change' } = {}
) {
  const field = fieldKey ? i18n.t(fieldKey) : ''
  const ruleKey = 'rule.' + actionType + 'Required'
  return {
    required: true,
    type,
    message: i18n.t(ruleKey, { field }),
    trigger
  }
}

// 生成长度规则配置
export function ruleLength(fieldKey, { min, max, trigger = 'change' } = {}) {
  const field = fieldKey ? i18n.t(fieldKey) : ''
  let ruleKey = 'rule.length'
  if (min) {
    ruleKey += 'Min'
  }
  if (max) {
    ruleKey += 'Max'
  }
  return {
    min,
    max,
    message: i18n.t(ruleKey, { field, min, max }),
    trigger
  }
}

// 生成正则表达式规则配置
export function ruleValidator(
  fieldKey,
  { validator, message, ruleKey, trigger = 'change' } = {}
) {
  const field = fieldKey ? i18n.t(fieldKey) : ''
  return {
    validator: (rule, value, callback) => {
      if (value && !validator(value)) {
        callback(new Error(message || i18n.t(ruleKey, { field })))
      } else {
        callback()
      }
    },
    trigger
  }
}

Vue.prototype.$rule = rules
